/**
 * 阿里云百炼文案改写服务
 * 使用通义千问API进行文案改写（OpenAI兼容模式）
 */

import OpenAI from "openai"

interface RewriteRequest {
  originalText: string
  prompt: string // 自定义改写提示词
}

interface RewriteResult {
  success: boolean
  rewrittenText?: string
  originalText: string
  prompt?: string
  error?: string
  requestId?: string
}

export default class AliyunTextRewriter {
  private openai: OpenAI

  constructor() {
    const apiKey = process.env.DASHSCOPE_API_KEY

    if (!apiKey) {
      throw new Error('DASHSCOPE_API_KEY environment variable is required')
    }

    this.openai = new OpenAI({
      apiKey: apiKey,
      baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
    })
  }

  /**
   * 改写单个文案
   */
  async rewriteText(request: RewriteRequest): Promise<RewriteResult> {
    try {
      const prompt = this.buildRewritePrompt(request)

      console.log('🚀 开始调用通义千问API改写文案...')
      console.log('📝 原始文案:', request.originalText)
      console.log('💬 用户提示词:', request.prompt)
      console.log('💬 发送给API的完整提示词:', prompt)

      const requestPayload = {
        model: "qwen-plus", // 使用qwen-plus模型
        messages: [
          { role: "system", content: "你是一个专业的文案改写助手，能够根据用户要求改写文案，保持原意的同时优化表达方式。" },
          { role: "user", content: prompt }
        ],
        temperature: 0.7, // 适中的创造性
        top_p: 0.8,
        max_tokens: 2000
      }

      console.log('📤 通义千问API请求参数:', JSON.stringify(requestPayload, null, 2))

      const completion = await this.openai.chat.completions.create(requestPayload)

      console.log('📥 通义千问API响应:', JSON.stringify(completion, null, 2))
      console.log('✅ 通义千问API调用成功')

      if (completion.choices && completion.choices[0] && completion.choices[0].message) {
        const rewrittenText = completion.choices[0].message.content

        console.log('📝 改写后文案:', rewrittenText)
        console.log('📊 Token使用情况:', completion.usage)

        return {
          success: true,
          rewrittenText: rewrittenText || '',
          originalText: request.originalText,
          prompt: request.prompt,
          requestId: completion.id
        }
      } else {
        throw new Error('Invalid API response structure')
      }
    } catch (error) {
      console.error('❌ 文案改写失败:', error)
      return {
        success: false,
        originalText: request.originalText,
        error: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 批量改写文案
   */
  async rewriteTexts(texts: string[], prompt: string): Promise<RewriteResult[]> {
    const results: RewriteResult[] = []

    for (const text of texts) {
      try {
        const result = await this.rewriteText({
          originalText: text,
          prompt
        })
        results.push(result)

        // 避免API限制，添加延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
      } catch (error) {
        results.push({
          success: false,
          originalText: text,
          error: error instanceof Error ? error.message : 'Unknown error'
        })
      }
    }

    return results
  }

  /**
   * 构建改写提示词
   */
  private buildRewritePrompt(request: RewriteRequest): string {
    let prompt = '请根据以下要求改写文案：\n\n'

    // 用户自定义要求
    prompt += `改写要求：\n${request.prompt}\n\n`

    prompt += '原文案：\n'
    prompt += `"${request.originalText}"\n\n`
    prompt += '请直接输出改写后的文案，不需要额外的解释或说明。'

    return prompt
  }


